package handler

import (
	"2301a/yuekao/api/request"
	"2301a/yuekao/consts"
	"2301a/yuekao/internal/dao"
	"2301a/yuekao/internal/model"
	"2301a/yuekao/pkg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func UserRegister(c *gin.Context) {
	var req request.UserRegisterReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "用户已存在",
			"data":    nil,
		})
		return
	}
	create := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: pkg.EncryptionMd5(req.Password),
		UType:    req.UType,
	})
	if !create {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "用户注册失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    true,
	})
}

func UserLogin(c *gin.Context) {
	var req request.UserLoginReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "用户不存在",
			"data":    nil,
		})
		return
	}
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID:          user.Id,
		AuthorityId: user.UType,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().UnixMilli() + 3600*24*7,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "生成token失败",
			"data":    nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登录成功",
		"data":    token,
	})
}

func RefreshToken(c *gin.Context) {
	userId := c.GetUint("userId")
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID: userId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().UnixMilli() + 3600*24*3,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "刷新token失败",
			"data":    nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "刷新token成功",
		"data":    token,
	})
}
